#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
============================================================================
    Desc: 添加到计划任务中，每小时检查一次
    Author: zhoubangjun
    Date: 2023/5/30 
=============================================================================
"""
import json
import logging
import os
from datetime import datetime

import requests
import yaml

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr

import sys
if sys.version_info.major < 3:
    reload(sys)
    sys.setdefaultencoding("utf-8")

base_dir = os.path.dirname(os.path.abspath(__file__))
config_file = os.path.join(base_dir, 'website_monitor_config.yml')
mail_info_file = os.path.join(base_dir, '.mail_info.json')
log_file = os.path.join(base_dir, 'website_monitor.log')


logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename=log_file, mode='w', encoding='utf-8')
handler.setFormatter(logging.Formatter("%(asctime)s-%(name)s-%(levelname)s: %(message)s"))
logger.addHandler(handler)


def website_monitor():
    check_result_list = []
    headers = {'user-agent': 'website_monitor'}

    config_info = yaml.load(open(config_file).read(), Loader=yaml.FullLoader)
    for project, info in config_info.items():
        http_info = info['http']
        name = http_info['name']
        url = http_info['url']

        try:
            result = requests.head(url=url, timeout=http_info['timeout'], headers=headers, allow_redirects=False)
        except Exception as e:
            logging.error('网站检查失败，网站名称: {}, Error: {}'.format(name, e))
            check_result_list.append('监控项目: {}, URL: {}, 状态: {}'.format(name, url, e.__class__.__name__))
            continue

        if result.status_code not in http_info['response_status_code']:
            check_result_list.append('监控项目: {}, URL: {}, 状态: {}'.format(name, url, result.status_code))

    logging.error('网站检查完毕')

    return '\n\n'.join(check_result_list)


def send_mail(data):
    with open(mail_info_file) as f:
        mail_info = json.load(f)

    smtp_host = mail_info['smtp_host']
    username = mail_info['username']
    password = mail_info['password']
    to_addr = mail_info['to_addr']
    cc_addr = mail_info.get('cc_addr')
    today = datetime.strftime(datetime.today(), '%Y-%m-%d')
    email_topic = '网站检查异常 - {}'.format(today).decode('utf-8')

    msg = MIMEText(data, 'plain', 'utf-8')
    msg['Subject'] = Header(email_topic)
    msg['From'] = formataddr(["paas", username])
    msg['To'] = ",".join(to_addr)
    if cc_addr:
        msg['Cc'] = ",".join(cc_addr)

    try:
        client = smtplib.SMTP(smtp_host, 25)
        client.starttls()
        client.login(username, password)
        client.sendmail(username, to_addr, msg.as_string())
        client.quit()
        logging.info('邮件发送成功！')
    except Exception as e:
        logging.error('邮件发送失败: {}'.format(e))


if __name__ == '__main__':
    data = website_monitor()
    if data:
        send_mail(data)
